package com.cn.ccp.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.service.course.FilePathService;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Converter;

@SuppressWarnings("serial")
public class UploadCourseFile extends HttpServlet {
	private Logger log = Logger.getLogger(UploadCourseFile.class);
	 
	public FilePathBean getFilePaht(){
		ServletContext servletContext = this.getServletContext();  
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
        return ((FilePathService) ctx.getBean("filePathService")).getFlagBean(); 
	}
	

	 private void unZipFiles(File file,String descDir)throws IOException{  
		 	ZipFile zipFile = new ZipFile(file);//实例化ZipFile，每一个zip压缩文件都可以表示为一个ZipFile
	        //实例化一个Zip压缩文件的ZipInputStream对象，可以利用该类的getNextEntry()方法依次拿到每一个ZipEntry对象
	        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"));
	        ZipEntry zipEntry = null;
	        File tempp = new File(descDir);
	        if(!tempp.exists())
	        	tempp.mkdirs();
	        
	        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
	            String fileName = zipEntry.getName();
	            File temp = new File(descDir + File.separator + fileName);
	            if(zipEntry.isDirectory()){
	            	if (! temp.exists())
	            		temp.mkdirs();
	            }else{
	            	if (! temp.getParentFile().exists())
	            		temp.getParentFile().mkdirs();
		            OutputStream os = new FileOutputStream(temp);
		            //通过ZipFile的getInputStream方法拿到具体的ZipEntry的输入流
		            InputStream is = zipFile.getInputStream(zipEntry);
		            int len = 0;
		            while ((len = is.read()) != -1)
		                os.write(len);
		            os.close();
		            is.close();
	            }
	        }
	        zipInputStream.close();
	  }    
	
	
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uid = request.getParameter("uid");
		String savePath = CCPContants.SYS_PATH+"files"+File.separator+ uid + File.separator ;
		FilePathBean filePathBean = getFilePaht();
		if(filePathBean != null){
			savePath = filePathBean.getPath()+uid+ File.separator ;
		}
		log.info(savePath);
		File f1 = new File(savePath);
		if (!f1.exists()) {
			f1.mkdirs();
		} 
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String sourseName = "";
		String extName = "";
		String fileName = ""; 
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				name = item.getName();
				sourseName = name ;
				log.info(name + " " + this);
				if (name == null || name.trim().equals("")) {
					continue;
				}
				//扩展名格式：  
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
					fileName = name.substring(0,name.lastIndexOf("."));
				}
				File file = null;
				do {
					//生成文件名：
					name = UUID.randomUUID().toString();
					file = new File(savePath + name + extName);
				} while (file.exists());
				File saveFile = new File(savePath + name + extName);
				try {
					log.info(saveFile.getCanonicalPath());
					item.write(saveFile);
					
					if(".zip".equalsIgnoreCase(extName)){
//						unZipFiles(saveFile,savePath);
						new UnZip(saveFile).start();
					}else{
					
						/**
						 * 对上传的文件进行处理
						 * 1、视频文件不做处理
						 * 2、swf文件不做处理
						 * 3、pdf文件不做处理
						 * 4、其他文字文件处理流程：源文件-》pdf文件。
						 */
						File pdfFile = new File(savePath + name + ".pdf");
						try {
							//判断是否为视频格式
							if(CCPContants.uploadVideoLayout.indexOf(extName.substring(1)) != -1){
								//是视频的话就直接保存，不用进行任何转换
								log.info("This is vedio file and do nothing for it..");
								Converter.encodeFile(saveFile);
							}else{
								if(extName.substring(1).equalsIgnoreCase("swf")){
									log.info("This is swf file and do nothing for it..");
									Converter.encodeFile(saveFile);
								}else if(extName.substring(1).equalsIgnoreCase("pdf")){
									log.info("This is pdf file and do nothing for it..");
									Converter.encodeFile(saveFile);
									//直接转换成swf文件
								}else{
									//需要先进行pdf转换，再进行swf转换
									pdfFile = Converter.convertTo(saveFile,"pdf");
									Converter.encodeFile(pdfFile);
									extName = ".pdf";
									saveFile.delete();
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							pdfFile.delete();
							response.getWriter().print(name + extName);
							return ;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
//		response.getWriter().print("files"+File.separator+ uid + File.separator + extName);
		response.getWriter().print(name + extName);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	class UnZip extends Thread{
		
		private File srcFile;
		UnZip(File srcFile){
			this.srcFile = srcFile;
		}
		public void run (){
			try {
				unZipFiles(srcFile,CCPContants.SYS_PATH + "tempfile"+ File.separator);
			} catch (IOException e) {
				log.error("Upload zip file failed : ", e); 
			}
		}
		
		
	}
	
	
	
	
	
	
}
